import chalk from 'chalk';
import ora, { Ora } from 'ora';
import fs from 'fs';
import path from 'path';
import os from 'os';

export class Logger {
  private static logFile = path.join(os.homedir(), '.cmodel-cli', 'debug.log');
  private static isDebug = process.env.DEBUG === 'true' || process.env.NODE_ENV === 'development';

  static info(message: string): void {
    console.log(chalk.blue('ℹ'), message);
  }

  static success(message: string): void {
    console.log(chalk.green('✓'), message);
  }

  static warning(message: string): void {
    console.log(chalk.yellow('⚠'), message);
  }

  static error(message: string): void {
    console.log(chalk.red('✗'), message);
  }

  static log(message: string): void {
    console.log(message);
  }

  static debug(message: string, data?: any): void {
    const timestamp = new Date().toISOString();
    const logMessage = data 
      ? `[${timestamp}] DEBUG: ${message}\n${JSON.stringify(data, null, 2)}\n`
      : `[${timestamp}] DEBUG: ${message}\n`;
    
    // 写入日志文件
    this.writeToFile(logMessage);
    
    // 如果是调试模式，也输出到控制台
    if (this.isDebug) {
      console.log(chalk.gray('🔍'), chalk.gray(message));
      if (data) {
        console.log(chalk.gray(JSON.stringify(data, null, 2)));
      }
    }
  }

  static spinner(text: string): Ora {
    return ora({
      text,
      color: 'blue'
    }).start();
  }

  private static writeToFile(message: string): void {
    try {
      const logDir = path.dirname(this.logFile);
      if (!fs.existsSync(logDir)) {
        fs.mkdirSync(logDir, { recursive: true });
      }
      fs.appendFileSync(this.logFile, message);
    } catch (error) {
      // 静默处理日志写入错误
    }
  }

  static getLogFile(): string {
    return this.logFile;
  }
}

export const logger = Logger;